<template>
  <div>
    <el-dialog v-model="dialogVisible" :title='ruleForm.id === 0 ? "新增房间" : "编辑房间"' width="500"
      :before-close="handleClose">
      <div>
        <el-form
          ref="ruleFormRef"
          style="max-width: 300px"
          :model="ruleForm"
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
          status-icon
        >
          <el-form-item label="房间号" prop="name">
            <el-input v-model="ruleForm.name" placeholder="请输入房间号" />
          </el-form-item>
          <el-form-item label="房间类型" prop="type">
            <el-select v-model="ruleForm.type" placeholder="请选择房间类型">
              <el-option v-for="item in listType" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="所属楼层" prop="buildingId">
            <el-cascader
              v-model="ruleForm.buildingId"
              :options="options"
              :props="{ label: 'name', value: 'id' }"
              style="width: 100%"
              @change="handleChange"
            />
          </el-form-item>
          <el-form-item label="床位数" prop="beds">
            <el-input v-model="ruleForm.beds" />
          </el-form-item>
          <el-form-item label="房间图片" prop="picture">
            <el-upload
              class="avatar-uploader"
              action="http://123.57.237.81:8080/caresystem/api/upload/add"
              :show-file-list="false"
              :headers="headers"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="ruleForm.picture" :src="imgUrl + ruleForm.picture" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="submit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import type { FormInstance, FormRules, UploadProps } from "element-plus";
import { houseAdd, houseUpdate } from "@/api/config/house/house";
import { buildingList } from "@/api/config/building/building";
import { addParams } from "@/api/config/house/type";
import { getToken } from "@/utils/auth";
import { buildTree } from "@/utils/treeUtil";
import { houseTypeList } from "@/api/config/houseType/houseType";
import { houseTypeListData } from "@/api/config/houseType/type";

const dialogVisible = ref(true);

const ruleForm = reactive<addParams>({
  id: 0,
  buildingId: 0,
  type: undefined,
  name: "",
  beds: undefined,
  picture: "",
});

const props = withDefaults(defineProps<{ listParams: addParams }>(), {
  listParams: () => ({
    id: 0,
    buildingId: 0,
    beds: 0,
    name: "",
    type: 0,
    picture: "",
  }),
});
Object.assign(ruleForm, props.listParams);

// 获取房间类型
const listType = ref<houseTypeListData[]>([]);
const getType = async () => {
  let res = await houseTypeList({ page: 1, pageSize: 999 });
  console.log("房间类型", res);
  listType.value = res.list;
};

// 选择楼栋
const options = ref([]);
const getBuildingList = async () => {
  let res = await buildingList();
  options.value = buildTree(res.list);
};
const handleChange = (value: any) => {
  ruleForm.buildingId = value[value.length - 1];
};

// 添加
const submitForm = async () => {
  let res = await houseAdd(ruleForm);
  console.log("添加", res);
  ElMessage.success("添加成功");
  emit("close");
};

// 修改
const update = async () => {
  let res = await houseUpdate(ruleForm);
  console.log("修改", res);
  ElMessage.success("修改成功");
  emit("close");
};

const submit = () => {
  ruleFormRef.value?.validate(async (valid) => {
    if (valid) {
      // submitForm()
      ruleForm.id === 0 ? await submitForm() : await update();
    }
  });
};

// 上传图片
const imgUrl = import.meta.env.VITE_IMG_URL; //获取图根路径
const headers = { Authorization: getToken() };

const handleAvatarSuccess: UploadProps["onSuccess"] = (response, uploadFile) => {
  ruleForm.picture = response.data.url;
};
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (
    rawFile.type !== "image/jpeg" &&
    rawFile.type !== "image/png" &&
    rawFile.type !== "image/webp"
  ) {
    ElMessage.error("只能上传jepg/png/webp格式的图片!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("上传的图片大小不能超过2MB!");
    return false;
  }
  return true;
};

// 表单校验
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules<addParams>>({
  name: [{ required: true, message: "请输入房间号", trigger: "blur" }],
  type: [
    {
      required: true,
      message: "请选择房间类型",
      trigger: "change",
    },
  ],
  buildingId: [
    {
      required: true,
      message: "请选择楼层",
      trigger: "change",
    },
  ],
  beds: [
    { required: true, message: '请输入床位数', trigger: 'blur' },
  ],
  picture: [
    { required: true, message: '请选择上传的房间图片', trigger: 'blur' },
  ],
})

// 关闭弹框
const emit = defineEmits(['close'])
const handleClose = () => {
  emit("close");
};

onMounted(() => {
  getType();
  getBuildingList();
});
</script>

<style scoped></style>
<style>
.avatar-uploader .el-upload {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  width: 80px;
  height: 80px;
  font-size: 28px;
  color: #8c939d;
  text-align: center;
}

.avatar {
  width: 80px;
  height: 80px;
}
</style>
